package com.ldatum.crm.daoImpl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;

import com.ldatum.crm.domain.TServices;
import com.ldatum.crm.service.TServicesDao;
import com.ldatum.crm.util.HibernateUtil;

public class TServicesDaoImpl implements TServicesDao {

	@Override
	public TServices findById(int id) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			TServices services = (TServices) s.get(TServices.class, id);
			Hibernate.initialize(services.getContacts());
			Hibernate.initialize(services.getCustomer());
			return services;
		}finally{
			if(s != null){
				s.close();
			}
		}
	}

	@Override
	public void save(TServices servicesBill) {
		HibernateUtil.add(servicesBill);
	}

	@Override
	public List<TServices> list(Class<TServices> class1, String session) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from TServices as services";
			Query q = s.createQuery(hql);
			@SuppressWarnings("unchecked")
			List<TServices> list = (List<TServices>) q.list();
			return list;
		}finally{
			if(s != null){
				s.close();
			}
		}
	}

	@Override
	public List<TServices> listToMe(Class<TServices> class1, String creater)
			throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from TServices as services where servicer = :servicer";
			Query q = s.createQuery(hql);
			q.setString("servicer", creater);
			@SuppressWarnings("unchecked")
			List<TServices> list = (List<TServices>) q.list();
			for(TServices ser:list){
				Hibernate.initialize(ser.getCustomer());
				Hibernate.initialize(ser.getContacts());
			}
			return list;
		}finally{
			if(s != null){
				s.close();
			}
			
		}
	}
	
	@Override
	public List<TServices> listByMe(Class<TServices> class1, String creater)
			throws Exception {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from TServices as services where creater = :creater";
			Query q = s.createQuery(hql);
			q.setString("creater", creater);
			@SuppressWarnings("unchecked")
			List<TServices> list = (List<TServices>) q.list();
			for(TServices ser:list){
				Hibernate.initialize(ser.getCustomer());
				Hibernate.initialize(ser.getContacts());
			}
			return list;
		}finally{
			if(s != null){
				s.close();
			}
		}
		
	}

	@Override
	public void update(TServices service) throws Exception {
		HibernateUtil.update(service);
	}

}
